<?php
/**
 * Measurement Model
 * 
 * @author CRIA Groep 1 <project@markvink.nl>
 * @version 1.0
 * @package models
 */
class Measurement extends AppModel 
{
	/**
    * @var string Model name (faster in PHP 4)
    */
	var $name = 'Measurement';
	
	/**
    * @var string displays field in select box
    */
	var $displayField = 'id';
			
	/**
    * @var array belongsTo relations
    */			
	var $belongsTo = array(
        'Laundry' => array(
            'className' => 'Laundry'
        ),
	);
	
	/**
    * @var array hasMany relations
    */	
	var $hasMany = array(
        'Production' => array(
            'className' => 'Production'
        ),
		'Usage' => array(
            'className' => 'Usage'
        ),
	);

	/**
    * @var array validation rules
    */
	var $validate = array( 
		'month' => array(            
			'rule' => array('range', 0, 13),                        
			'message' => 'Please select a number valid month'            
		),	
		'year' => array(            
			'rule' => array('checkYear', 2),                        
			'message' => 'Please select a valid year'            
		),		
	);
	
	/**
	 * Custom validation rule checkYear
	 * 
	 * Check if given year is in valid range
	 * @param array $check data
	 * @param string $range range
	 * @return boolean
	 */
	function checkYear($check, $range){   
		return ($check['year'] >= date('Y')-$range && $check['year'] <= date('Y'));   
	}
	
	/**
	 * Function findByMeasurementData
	 * 
	 * find data for a measurement
	 * @param integer $laundry laundry_id
	 * @param integer $year year
	 * @param integer $month month
	 * @return array
	 */
	function findByMeasurementData($laundry, $year, $month) {
		$measurement = $this->find('first', array(
			'conditions' => array(
				'Measurement.laundry_id' => $laundry,
				'Measurement.year' => $year,
				'Measurement.month' => $month,
			)
		));
		
		if(empty($measurement)) {
			$data = array('Measurement' => array(
				'laundry_id' => $laundry,
				'year' => $year,
				'month' => $month,
			));
			$this->save($data);
			$measurement = $this->read(null, $this->id);
		}
		return $measurement;
	}
	
	/**
	 * Function __getNeighbors
	 * 
	 * find neightbors for measurment
	 * @param array $measurement measurement
	 * @return array
	 */
	function __getNeighbors($measurement) {
		$date = mktime(0, 0, 0, $measurement['Measurement']['month'], 1, $measurement['Measurement']['year']);
		$prevDate = strtotime('-1 month', $date);
		$nextDate = strtotime('+1 month', $date);
		
		$prev = $this->findByMeasurementData($measurement['Measurement']['laundry_id'], date('Y', $prevDate), date('n', $prevDate));
		$next = $this->findByMeasurementData($measurement['Measurement']['laundry_id'], date('Y', $nextDate), date('n', $nextDate));
		
		return array(
			'prev' => $this->__foreachDataArray($prev, array('Production', 'Usage')),
			'next' => $this->__foreachDataArray($next, array('Production', 'Usage')),
		);
	}
	
	/**
	 * Function __foreachDataArray
	 * 
	 * Change dataarray for given models
	 * @param array $array dataarray
	 * @params array $models
	 * @return array
	 */
	function __foreachDataArray($array, $models) {
		$data = array();
		if(is_array($array) && is_array($models)) {
			foreach($models AS $model) {
				if(is_array($array[$model])) {
					foreach($array[$model] AS $dataarray) {
						$data[ucfirst($model)][$dataarray[strtolower($model) . 'type_id']] = $dataarray['amount'];
					}
				}
			}
		}
		return $data;
	}
	
	/**
	 * Function findAvgByYear
	 * 
	 * Find average
	 * @param integer $year year
	 * @param string $model related model
	 * @param integer $id related model type id
	 * @return array
	 */
	function findAvgByYear($year, $model, $id) {
		$return = array();
		$dbo = $this->getDataSource();
		$subQuery = $dbo->buildStatement(array(
			'fields' => array(
				'CAST(AVG(amount) AS DECIMAL(10,0)) AS amount',
				'Measurement.month'
			),
			'table' => $dbo->fullTableName($this),
			'alias' => 'Measurement',
			'limit' => null,        
			'offset' => null,        
			'joins' => array(
				array(
					'table' => Inflector::tableize($model),        
					'alias' => Inflector::singularize($model),        
					'type' => 'LEFT',        
					'conditions' => array(            
						'Measurement.id = ' . Inflector::singularize($model) . '.Measurement_id',        
					)    
				)
			),
			'conditions' => array(
				'Measurement.year' => $year,
				Inflector::singularize($model) . '.' . Inflector::singularize($model) . 'type_id' => $id
			),
			'order' => null,
			'group' => array(
				'Measurement.month'
			)
		), $this);
		
		foreach($this->query($subQuery) AS $measurement) {
			$return[intval($measurement['Measurement']['month'])] = intval($measurement[0]['amount']);
		}
		return $return;
	}
}
